package com.library.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.library.dao.UserDAO;
import com.library.entity.User;

/**
 * 管理员用户管理Servlet
 */
@WebServlet("/admin/user")
public class AdminUserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String action = request.getParameter("action");
        
        if (action == null) {
            // 默认显示所有用户
            showAllUsers(request, response);
        } else if (action.equals("edit")) {
            // 显示编辑用户表单
            editUser(request, response);
        } else if (action.equals("delete")) {
            // 删除用户
            deleteUser(request, response);
        } else if (action.equals("search")) {
            // 搜索用户
            searchUsers(request, response);
        } else {
            // 默认显示所有用户
            showAllUsers(request, response);
        }
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String action = request.getParameter("action");
        
        if (action.equals("edit")) {
            // 更新用户
            updateUser(request, response);
        } else {
            // 默认显示所有用户
            showAllUsers(request, response);
        }
    }
    
    // 显示所有用户
    private void showAllUsers(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        UserDAO userDAO = new UserDAO();
        List<User> users = userDAO.getAllUsers();
        
        request.setAttribute("users", users);
        request.getRequestDispatcher("/admin/users.jsp").forward(request, response);
    }
    
    // 显示编辑用户表单
    private void editUser(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        
        UserDAO userDAO = new UserDAO();
        User user = userDAO.getUserById(id);
        
        request.setAttribute("user", user);
        request.getRequestDispatcher("/admin/edit_user.jsp").forward(request, response);
    }
    
    // 更新用户
    private void updateUser(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 获取表单数据
        int id = Integer.parseInt(request.getParameter("id"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String realName = request.getParameter("realName");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        int role = Integer.parseInt(request.getParameter("role"));
        
        // 创建用户对象
        User user = new User(username, password, realName, email, phone, role);
        user.setId(id);
        
        // 更新用户信息
        UserDAO userDAO = new UserDAO();
        boolean success = userDAO.updateUser(user);
        
        if (success) {
            // 更新成功，重定向到用户列表
            response.sendRedirect("user");
        } else {
            // 更新失败，返回编辑表单并显示错误信息
            request.setAttribute("error", "更新用户失败，请稍后再试");
            request.setAttribute("user", user);
            request.getRequestDispatcher("/admin/edit_user.jsp").forward(request, response);
        }
    }
    
    // 删除用户
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        
        // 不能删除自己
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        User currentUser = (User) httpRequest.getSession().getAttribute("user");
        
        if (currentUser.getId() == id) {
            request.setAttribute("error", "不能删除自己的账户");
            showAllUsers(request, response);
            return;
        }
        
        UserDAO userDAO = new UserDAO();
        boolean success = userDAO.deleteUser(id);
        
        if (success) {
            // 删除成功，重定向到用户列表
            response.sendRedirect("user");
        } else {
            // 删除失败，重定向到用户列表并显示错误信息
            request.setAttribute("error", "删除用户失败，请稍后再试");
            showAllUsers(request, response);
        }
    }
    
    // 搜索用户
    private void searchUsers(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        
        UserDAO userDAO = new UserDAO();
        List<User> users = userDAO.getAllUsers(); // 简化处理，实际应按关键词搜索
        
        // 过滤用户列表
        List<User> filteredUsers = new ArrayList<>();
        for (User user : users) {
            if (user.getUsername().contains(keyword) || 
                user.getRealName().contains(keyword) || 
                user.getEmail().contains(keyword)) {
                filteredUsers.add(user);
            }
        }
        
        request.setAttribute("users", filteredUsers);
        request.setAttribute("keyword", keyword);
        request.getRequestDispatcher("/admin/users.jsp").forward(request, response);
    }
}
